<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <c-select
          clearable
          placeholder="产品类型"
          v-model="params['is_rural_dev.eq']"
          @change="getAllData()"
          :options="{
            1: '乡村振兴贷',
            0: '黔农十二贷',
          }"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params['channel_type.eq']"
          @change="getAllData()"
          placeholder="业务模式"
          :options="{
            0: '存量业务',
            1: '增量业务',
          }"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-child-bank
          clearable
          v-model="params['bank_id.eq']"
          @change="getAllData()"
          placeholder="导入银行(可输入过滤)"
        ></select-child-bank>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="params['is_history.eq']"
          clearable
          placeholder="是否历史数据"
          :options="{
            0: '历史数据(否)',
            1: '历史数据(是)',
          }"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="是否银行直连"
          :options="{
            0: '否',
            1: '是',
          }"
          v-model="params['is_dir.eq']"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="导入日期(含)"
          end-placeholder="导入日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate2"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="放款日期(含)"
          end-placeholder="放款日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery2"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="queryDate3"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="审批日期(含)"
          end-placeholder="审批日期(含)"
          value-format="yyyy-MM-dd"
          @change="handleDateQuery3"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="{
            bank_id: '按导入银行统计',
            claim_bank_name: '按放款银行统计',
            apply_bank_id: '按提交银行统计',
          }"
          v-model="groupType"
          @change="setGroupType"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="客户区域查询"
          auto-top
          :bottom-level="2"
          clearable
          @change="getAllData()"
        ></select-address>
      </el-form-item>

      <el-form-item>
        <c-select
          placeholder="项目状态"
          :options="{
            1: '新增(本年1月至今)',
            2: '在保',
            3: '解保',
            4: '代偿',
          }"
          v-model="projectStatus"
          clearable
          @change="setProjectParams"
        ></c-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="getAllData()">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="card my-2">
      <div class="card-body" v-loading="countLoading">
        <span class="h5 text-muted">
          项目共计：
          <span class="text-danger">{{ tableCount }}</span>
        </span>
        <span class="h5 text-muted ml-5">
          金额合计：
          <span class="text-danger">{{ tableFunds || '-' }}</span>
          万元
        </span>
      </div>
      <div class="pl-3 pb-3">
        <div class="text-warning">
          查询某月数据，时间范围选择同一个月即可(数据只包含审批完成的项目，审批中项目未统计)
        </div>
        <div class="text-warning">详细数据可以点击表格某一行查看详细数据</div>
      </div>
    </div>
    <c-table
      border
      class="table-sm"
      v-loading="loading"
      :columns="tableColumns"
      :data="tableData"
      @row-click="selectRow"
    ></c-table>

    <detail-dialog :visible.sync="viewVisible" :other-params="otherParams"></detail-dialog>
  </div>
</template>

<script>
import DetailDialog from '@/bank/views/business/count/DetailDialog'
import hndTableMixin from '@/bank/views/business/limit/history/mixins'
import SelectChildBank from '@/bank/components/select/SelectChildBank'
import SelectAddress from '@/components/select/SelectAddress'
export default {
  components: {
    SelectChildBank,
    DetailDialog,
    SelectAddress,
  },
  mixins: [hndTableMixin],
  data() {
    return {
      loading: false,
      tableName: 'datum_one_county_industry',
      tableData: [],
      tableColumns: [
        { attrs: { label: '机构名称', prop: 'bankName' } },
        { attrs: { label: '项目数', prop: 'p' } },
        { attrs: { label: '担保金额', prop: 'p1' } },
      ],
      params: {
        groupFields: 'bank_id',
        fields: ['bank_id,bank_name', 'apply_bank_id', 'apply_bank_name', 'claim_bank_name'],
        groupFunc:
          'count(datum_one_county_industry.customer_related_id),round(sum(warranty_amount)|2)',
        create_time: '',
        'review_approval.in': '4,5,6,7',
      },

      viewVisible: false,
      otherParams: {},
      countLoading: false,
      tableCount: 0,
      tableFunds: 0,
      queryDate: [],
      queryDate2: [],
      queryDate3: [],
      groupType: 'bank_id',
      enumBankName: {
        bank_id: 'bank_name',
        claim_bank_name: 'claim_bank_name',
        apply_bank_id: 'apply_bank_name',
      },
      notAddressCode: '',

      projectStatus: '',
      seachParams: {},
    }
  },

  created() {
    this.getAllData()
  },
  methods: {
    setGroupType(val) {
      this.params.groupFields = val
      this.getAllData()
    },
    setProjectParams(status) {
      this.params['create_time.gte'] = ''
      this.params['review_approval.eq'] = ''
      this.params['review_approval.in'] = '4,5,6,7'
      this.params['is_compens.eq'] = ''
      switch (+status) {
        case 1:
          this.params['create_time.gte'] = `${new Date().getFullYear()}-01-01 00:00:00`
          break
        case 2:
          this.params['review_approval.eq'] = 4
          break
        case 3:
          this.params['review_approval.in'] = '5,6,7'
          break
        case 4:
          this.params['is_compens.eq'] = 1
          break
        default:
          break
      }
      this.getAllData()
    },
    getSelectDates(data) {
      if (!data || !data.length) {
        return ['', '']
      }
      let startTime = ''
      let endTime = ''
      const date = new Date(data[0])
      startTime = date
        ? `${date.getFullYear()}-${(date.getMonth() + 1 + '').padStart(2, 0)}-${date.getDate()}`
        : ''
      endTime = date
        ? `${new Date(data[1]).getFullYear()}-${(new Date(data[1]).getMonth() + 2 + '').padStart(
            2,
            0
          )}-${new Date(data[1]).getDate()}`
        : ''
      return [startTime, endTime]
    },
    handleDateQuery3() {
      const dates = this.getSelectDates(this.queryDate3)
      this.params['approval_time.gte'] = dates[0]
      this.params['approval_time.lt'] = dates[1]
      this.getAllData()
    },
    handleDateQuery2() {
      const dates = this.getSelectDates(this.queryDate2)
      this.params['load_date.gte'] = dates[0]
      this.params['load_date.lt'] = dates[1]
      this.getAllData()
    },
    handleDateQuery() {
      const dates = this.getSelectDates(this.queryDate)
      this.params['create_time.gte'] = dates[0]
      this.params['create_time.lt'] = dates[1]
      this.getAllData()
    },
    getAllData() {
      this.params = { ...this.params, ...this.normalParams, 'import_status.eq': '' }
      this.getData()
      this.getCountData()
    },
    selectRow(row) {
      this.otherParams = {
        ...this.params,
        groupFields: '',
        fields: '',
        groupFunc: '',
      }
      this.otherParams[`${this.groupType}.eq`] = row[this.groupType]
      this.viewVisible = true
    },
    getCountData() {
      this.$api
        .getData(
          'credit',
          this.tableName,
          { ...this.params, groupFields: '' },
          { bank_type: 'asc' }
        )
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.tableCount = data.p || 0
          this.tableFunds = data.p1 || 0
        })
    },
    dataAdapter(item) {
      item.bankName = item[this.enumBankName[this.groupType]]
      return item
    },
    getData() {
      this.loading = true
      this.$api
        .getData('credit', this.tableName, this.params, { bank_name: 'asc' })
        .then(res => {
          this.tableData = (res.data || []).map(this.dataAdapter)
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped></style>
